package org.example.misc.config;


import com.alibaba.fastjson.JSON;
import org.example.misc.exception.ServiceException;
import org.example.misc.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.List;

public class BaseWebMvcConfigurer implements WebMvcConfigurer {
    private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class);

    /**
     * 异常处理器
     * @param resolvers
     */
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        HandlerExceptionResolver resolver = (request, response, handler, exception) -> {
            Result<Object> result = new Result<>();
            if (exception instanceof ServiceException) {
                // 内部业务异常
                result.setHttpCode(HttpStatus.OK).setMessage(exception.getMessage());
                result.setServerCode(((ServiceException) exception).getErrorCode());
                logger.info(exception.getMessage());
            } else if (exception instanceof NoHandlerFoundException) {
                result.setHttpCode(HttpStatus.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在");
            } else if (exception instanceof ServletException) {
                result.setHttpCode(HttpStatus.BAD_REQUEST);
                result.setMessage(exception.getMessage());
            } else {
                result.setHttpCode(HttpStatus.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误，请联系管理员");
                String errorLogInfo;
                if (handler instanceof HandlerMethod) {
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    errorLogInfo = String.format("接口 [%s] 出现异常，方法：%s.%s，异常摘要：%s",
                            request.getRequestURI(),
                            handlerMethod.getBean().getClass().getName(),
                            handlerMethod.getMethod().getName(),
                            exception.getMessage());
                } else {
                    errorLogInfo = exception.getMessage();
                }
                logger.error(errorLogInfo, exception);
            }
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setStatus(200);
            try {
                response.getWriter().write(JSON.toJSONString(result));
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
            return new ModelAndView();
        };
        resolvers.add(resolver);
    }

    /**
     * 跨域处理
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}
